#-*- coding:utf-8 -*-
'''
Created on Jun 24, 2012

@author: bbg
'''


from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE,formatdate
import smtplib  
from helper.login_session_manager import LoginSessionManager
from helper.cdkey_manager import CdkeyManager 
import dbwrapper
from dbwrapper.companyx.user_right import UserRight
from dbwrapper.company_management.company import Company
from dbwrapper.companyx.shop import Shop
from dbwrapper.companyx.login_session import LoginSession
import json
from service_base import ServiceBase 
from common.debug import Debug
import cgi
import cStringIO
import sys
import os


class Applyshenghe(ServiceBase):

    
    def __init__(self, start_response):
        
        ServiceBase.__init__(self, start_response)
        self.debug = Debug()
        self.debug.d("begin come into Applyshenghe")

    
    
   
    def application(self, params):

        #params = parse(None, environ)
        debug=Debug()
        debug.d("wugang123 CC")
        self.debug.d("DDD:%s" % repr(params))
        
        login_type = params.getfirst('type')
        if login_type == '0': # client login
            return self._webLogin(params)
        elif login_type == '1': # web login
            return self._webLogin(params)
        
        return self._responseError(-1,'invalid path ')
    


    
    def applysub(self, params):  
        client_type = params.getfirst('type')
        if client_type == '0': # client login
            return self._webapplycompany(self,params) 
        elif client_type == '1': # web login
            return self._webapplycompany(self,params)         
        return self._responseError('-1','error ')

   
    @staticmethod         
    def _webapplycompany(self, request_params):
        '''
                    负责公司层面 审核
        '''        
        self.debug.d("begin come into _webapplycompany")   
        company_id = request_params.getfirst('company_id')
        dangqian_id = request_params.getfirst('dangqian_id')        
        username = request_params.getfirst('username')         
        token = request_params.getfirst('token')           
        if company_id == None or dangqian_id == None or username == None or token == None:
            return self._responseError(-1,'invalid ')
        
        #核实企业ID是否存在
        dbsession = dbwrapper.MySqlSession()
        companyb =dbsession.query(Company).filter(Company.id ==int(company_id)).filter(Company.state ==0)        
        if companyb.count() == 0:            
            return self._responseError(-1,'not exit')
        
        #检查TOKEN是否过期
        intcomp = LoginSessionManager.isValidSession(dangqian_id, username, token, dbsession)        
        if intcomp==False:
            return self._responseError(-1,'已经过期')
                         

                         
        dbsession.commit()
        dbsession.execute(" create database company_%s     DEFAULT CHARACTER SET utf8  " % company_id)
        dbsession.commit()
        dbsession.execute("use company_%s " % company_id)
        dbsession.commit()
        response_paramsARRAY = []
        all_sql=""
        content=" use `company_%s`    ; " % company_id
        file_object = open('/home/dev/website/dbbase/company_1.sql', 'r')
        try:
            for f_line in file_object.readlines():
                all_sql=unicode(f_line, 'utf-8')   
                content = content+all_sql
            dbsession.execute(content)
            dbsessionsec =self._returndbsession()
            companyCC =dbsessionsec.query(Company).filter(Company.id ==int(company_id)).filter(Company.state ==0).first()        
            companyCC.state=1      
            dbsessionsec.commit()     
            
            '''
                                 发送email 给客户
            '''
            email=companyCC.email
            kehuname=companyCC.name
            contact=companyCC.contact
            sendto=[]
            sendto.append("1569195042@qq.com")   
            sendto.append(email)   
            server= {}
            server["name"]="smtp.qq.com"
            server["user"]="1569195042@qq.com"
            server["passwd"]="wad123!@"
            fro="1569195042@qq.com"
            subject="艾博科技->艾云服务审核通过"
            sendtextb="尊敬的艾云用户：%s   \n 您好   \n  贵公司 :  %s \n 已经通过艾博科技审核  " % (contact.encode('utf-8'),kehuname.encode('utf-8'))            
            self._send_mail(self,server, fro, sendto, subject, sendtextb)

            
                               
            response_paramsb = {}
            response_paramsb["id"]=company_id
            response_paramsb["msg"]="success"
            response_paramsb["success"]="1"                         
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)      
            
        finally:
            file_object.close()
        #response_paramsARRAY.append(response_params)
        return self._response(json.dumps(response_paramsARRAY))
                    
 
 


    def webapplyshop(self, request_params):
        '''
            负责分店层面 审核
        '''        
        company_id = request_params.getfirst('company_id')
        dangqian_id = request_params.getfirst('dangqian_id')        
        username = request_params.getfirst('username')         
        token = request_params.getfirst('token')    
        shopid= request_params.getfirst('shopid')        
        if company_id == None or dangqian_id == None or username == None or token == None or shopid==None:
            return self._responseError(-1,'invalid')
        
        #核实企业ID是否存在
        dbsession = self._returndbsession()
        Shop.doMapping(company_id)
        shop =dbsession.query(Shop).filter(Shop.id ==int(shopid)).filter(Shop.state ==0)        
        if shop.count() == 0:            
            return self._responseError(-1,'not exit')
        
        #检查TOKEN是否过期
        intcomp = LoginSessionManager.isValidSession(dangqian_id, username, token, dbsession)        
        if intcomp==False:
            return self._responseError(-1,'已经过期')
                         

                         
        dbsession.commit()
        dbsession.execute(" create database shop_%s_%s     DEFAULT CHARACTER SET utf8  " % (company_id,shopid))
        dbsession.commit()
        dbsession.execute("use `shop_%s_%s` " % (company_id,shopid))
        dbsession.commit()
        response_paramsARRAY = []
        all_sql=""
        content=" use `shop_%s_%s`   ; " % (company_id,shopid)
        file_object = open('/home/dev/website/dbbase/shop_1_1.sql', 'r')
        try:
            for f_line in file_object.readlines():
                all_sql=unicode(f_line, 'utf-8')   
                self.debug.d(all_sql)             
                content = content+all_sql
            dbsession.execute(content)
            dbsessionsec = self._returndbsession()
            Shop.doMapping(company_id)
            shopcc =dbsessionsec.query(Shop).filter(Shop.id ==int(shopid)).filter(Shop.state ==0).first()        
            shopcc.state=1   
            dbsessionsec.commit()      
            '''
                                 发送email 给客户
            '''
            email=shopcc.email
            kehuname=shopcc.name
            contact=shopcc.contact
            sendto=[]
            sendto.append("1569195042@qq.com")   
            sendto.append(email)   
            
            server= {"name" : "smtp.qq.com", "user" : "1569195042@qq.com", "passwd" : "wad123!@"}
            fro="1569195042@qq.com"
            subject="艾博科技->艾云服务审核通过"
            sendtextb="尊敬的艾云用户：%s   \n 您好   \n  贵公司 旗下门店:  %s \n 已经通过艾博科技审核  " % (contact.encode('utf-8'),kehuname.encode('utf-8'))
            self._send_mail(self,server, fro, sendto, subject, sendtextb)
           
                              
            response_paramsb = {}
            response_paramsb["id"]=shopid
            response_paramsb["msg"]="success"
            response_paramsb["success"]="1"                         
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)      
            
        finally:
            file_object.close()
        #response_paramsARRAY.append(response_params)
        return self._response(json.dumps(response_paramsARRAY))
                    

    @staticmethod
    def _send_mail(self,server, fro, to, subject, text):
        assert type(server) == dict
        assert type(to) == list
 
        try:
            self.debug.d("emailcodeBBB1:") 
            msg = MIMEMultipart() 
            self.debug.d("emailcodeBBB2:") 
            msg['From'] = fro 
            self.debug.d("emailcodeBBB3:") 
            msg['Subject'] = subject 
            self.debug.d("emailcodeBBB4:") 
            msg['To'] = COMMASPACE.join(to) #COMMASPACE==', ' 
            self.debug.d("emailcodeBBB5:") 
            msg['Date'] = formatdate(localtime=True) 
            self.debug.d("emailcodeBBB6:") 
            msgtext=MIMEText(text, "plain")
            msg.attach(msgtext)
            self.debug.d("emailcodeBBB7:") 
            
            self.debug.d("emailcodeBBB8:") 
            smtp=smtplib.SMTP()
            self.debug.d("emailcodeCCC9:") 
            smtp.connect(server["name"])
            self.debug.d("emailcodeDDD10:")             
            code = smtp.ehlo()[0]
            self.debug.d("emailcode:%d" % code) 
            smtp.login(server["user"],server["passwd"])
            smtp.sendmail(fro, to, msg.as_string()) 
            smtp.close()
        except (smtplib.SMTPException),e:
            self.debug("erroremail::%s" % e)
            
            
        return
            
        
        
    
    
if __name__ == '__main__':
    def start_response(a, b):
        pass
    

        
        
        